﻿using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
 

namespace RabbitMqDemo.HosteServices
{
    public class RabbitMqConsumer : IHostedService
    {

        IConnection connection;
        IModel channel;

        public Task StartAsync(CancellationToken cancellationToken)
        {
            ConnectionFactory factory = new ConnectionFactory();
            factory.UserName = "admin-test";
            factory.Password = "123456";
            factory.VirtualHost = "/";
            factory.HostName = "192.168.2.113";
            // factory.Port = 1884;
            factory.Port = 5672;

            connection = factory.CreateConnection("sunyuliangConsumer");
            channel = connection.CreateModel();
            var consumer=new EventingBasicConsumer (channel);
            consumer.Received += Consumer_Received;
 
            string consumerTag = channel.BasicConsume("MqTest", false, consumer);
            return Task.CompletedTask;
        }
 

        private void  Consumer_Received(object? _sender, BasicDeliverEventArgs e)
        {
            var sender = _sender as EventingBasicConsumer;
            var msg = Encoding.UTF8.GetString(e.Body.ToArray());
            Console.WriteLine("消费：" + msg);
            sender.Model.BasicAck(e.DeliveryTag, false);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            channel.Close();
            connection.Close();

            return Task.CompletedTask;
        }
    }
}
